<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="区县编码" prop="adcode">
        <el-input
          v-model="queryParams.adcode"
          placeholder="请输入区县编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['factoryArea:factoryArea:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['factoryArea:factoryArea:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['factoryArea:factoryArea:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['factoryArea:factoryArea:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="factoryAreaList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column show-overflow-tooltip label="范围" align="center" prop="scope"/>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="区县编码" align="center" prop="adcode" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['factoryArea:factoryArea:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['factoryArea:factoryArea:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改厂区范围对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="区县编码" prop="adcode">
          <el-select style="width: 100%" v-model="form.adcode" placeholder="请输入区县编码">
            <el-option v-for="item in adcodesList" :key="item.code" :label="item.name" :value="item.code"/>
          </el-select>
        </el-form-item>
        <el-form-item label="范围" prop="scope">
          <el-input disabled v-model="form.scope" placeholder="请输入内容" >
            <el-button @click="showCoordinate" size="mini" slot="append">范围拾取</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="坐标拾取" :visible.sync="coordinate" width="1000px" append-to-body>
      <div style="display: flex;justify-content: space-between;margin-bottom: 30px">
        <div>
          <el-select style="width: 30%;margin-right: 10px" v-model="mapCity"
                     filterable
                     placeholder="请选择"
                     @change="handleSearch"
          >
            <el-option-group
              v-for="area in areaJson"
              :key="area.name"
              :label="area.name"
            >
              <el-option
                v-for="item in area.citys"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-option-group>
          </el-select>
          <el-input placeholder="地址" @input="handleSearch" v-model="city" style="width: 50%"></el-input>
        </div>
        <div style="width: 40%">
          <el-button @click="drawFactoryArea" type="primary">开始绘制厂区范围</el-button>
          <el-button @click="empty" type="danger">清空</el-button>
<!--          <el-input placeholder="经度" v-model="lng" disabled style="width: 30%;margin-right: 10px"></el-input>-->
<!--          <el-input placeholder="纬度" v-model="lat" disabled style="width: 30%;margin-right: 10px"></el-input>-->
          <el-button @click="saveLatOrLng" type="primary">确定</el-button>
        </div>
      </div>
      <div>
        <el-header height="40px"
                   style="background-color: #f6f6f6;
                   border: 1px solid #e3e3e3;display: flex;
                   align-items: center;justify-content: space-between">
          <div>
            <span style="font-weight: bold">{{ mapCity }}，</span>
            <span style="font-size: 10px">缩放等级：{{ mapZoomLevel }}</span>
          </div>
          <div>
            <span style="font-size: 12px">{{ geographiclocationInformation }}</span>
          </div>
        </el-header>
        <el-container style="height: 500px; border: 1px solid #eee">
          <el-aside style="padding:0">
            <div v-if="city">
              <div v-if="addressList.length > 0">
                <div
                  class="map_list"
                  :id="item.id"
                  :class="{ active: item.active || item.hover }"
                  v-for="(item, index) in addressList"
                  @click="selectAddress(item)"
                  :key="index"
                >
                  <span style="font-weight: bold">{{ index + 1 }}：{{ item.name }}</span><br/>
                  <span style="font-size: 10px">地址：{{ item.address }}</span><br/>
                  <span style="font-size: 10px">电话：{{ item.tel }}</span><br/>
                  <span style="font-size: 10px">坐标：{{ item.location.lat.toFixed(6) }}，{{
                      item.location.lng.toFixed(6)
                    }}</span><br/>
                </div>
              </div>
              <div class="map_empty" v-else>对不起，没有搜索到你要找的结果</div>
            </div>
            <div class="map_empty" v-else>
              <span style="font-weight: bold">功能简介：</span><br/>
              <span style="font-size: 10px">1、支持地址 精确/模糊 查询</span><br/>
              <span style="font-size: 10px">2、支持POI点坐标显示</span><br/>
              <span style="font-size: 10px">3、支持范围绘制，点击开始绘制按钮后，从地图上开始绘制，绘制完成后双击结束绘制</span><br/>
              <span style="font-weight: bold">使用说明：</span><br/>
              <span style="font-size: 10px">在搜索框搜索关键词后，地图上会显示相应poi点，
                同时左侧显示对应该点的信息，点击某点或某信息，右上角会显示相应该点的地址。</span>
            </div>
          </el-aside>
          <el-main id="myMap" class="myMap"></el-main>
        </el-container>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFactoryArea, getFactoryArea, delFactoryArea, addFactoryArea, updateFactoryArea } from "@/api/company/factoryArea";
import AMapLoader from '@amap/amap-jsapi-loader'
import areaJson from '@/common/map_area'
import util from '@/common/util'

export default {
  name: "FactoryArea",
  data() {
    return {
      //地图缩放等级
      mapZoomLevel: 11,
      //地理位置信息
      geographiclocationInformation: '',
      //范围经纬度JSON数据
      overlays:[],
      mouseToolList:[],
      coordinate:false,
      //全国市名称数据
      areaJson: [],
      mapCity: '',
      map: null,
      AMap: null,
      city: '',
      addressList: [],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // factoryArea表格数据
      factoryAreaList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        adcode: null,
      },
      //聊城市各区县名称和code
      adcodesList:[
        {
          name:'高唐县',
          code:'371526',
        },{
          name:'临清市',
          code:'371581',
        },{
          name: '茌平区',
          code: '371503',
        },{
          name: '冠县',
          code: '371525',
        },{
          name: '东昌府区',
          code: '371502',
        },{
          name: '东阿县',
          code: '371524',
        },{
          name: '莘县',
          code: '371522',
        },{
          name: '阳谷县',
          code: '371521',
        }
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name:[
          {required: true,message:'请输入名称', trigger:'blur'}
        ],
        adcode: [
          { required: true, message: "区县编码不能为空", trigger: "blur" }
        ],
        scope: [
          {required: true, message: '范围不能为空', trigger: 'blur'}
        ]
      },
    };
  },
  created() {
    this.getList();
    this.areaJson = areaJson.areas
  },
  methods: {
    /** 查询厂区范围列表 */
    getList() {
      this.loading = true;
      listFactoryArea(this.queryParams).then(response => {
        this.factoryAreaList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //范围拾取弹窗
    showCoordinate() {
      // this.form.scope = ''
      this.coordinate = true
      this.initializeMap()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        scope: null,
        remark: null,
        adcode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    //初始化地图
    initializeMap() {
      let that = this
      let map = null
      let geocoder = null
      let infoWindow = null
      window._AMapSecurityConfig = {
        securityJsCode: '41e17bd194dc80120ab5e431f6e5264e'
      }
      AMapLoader.load({
        'key': 'e9f5683c5fe13b606dc1179f1e503062',              // 申请好的Web端开发者Key，首次调用 load 时必填
        'version': '2.0',                                       // 指定要加载的 JS API 的版本，缺省时默认为 1.4.15
        'plugins': ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType', 'AMap.Geolocation', 'AMap.Geocoder', 'AMap.InfoWindow']                                          // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        map = new AMap.Map('myMap', {
          resizeEnable: true,
          zoom: that.mapZoomLevel
        })
        that.map = map
        that.AMap = AMap
        // 地图添加各种控件
        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
        map.addControl(new AMap.ToolBar())
        // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
        map.addControl(new AMap.MapType())
        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
        map.addControl(new AMap.Scale())
        //根据经纬度获取地理位置信息
        geocoder = new AMap.Geocoder({
          radius: 1000, //以已知坐标为中心点，radius为半径，返回范围内兴趣点和道路信息
          extensions: 'all' //返回地址描述以及附近兴趣点和道路信息，默认“base”
        })
        //获取当前位置信息
        that.getCityService()
        // infoWindow = new AMap.InfoWindow({
        //   offset: new AMap.Pixel(16, 0)
        // })
        // map.on('mousemove', function(e) {
        //   //鼠标点击marker弹出自定义的信息窗体
        //   // infoWindow.setContent(`${e.lnglat.lng},${e.lnglat.lat}`)
        //   // infoWindow.open(map, [e.lnglat.lng, e.lnglat.lat])
        // })
        map.on('click', function(e) {
          // that.lng = e.lnglat.lng
          // that.lat = e.lnglat.lat
          geocoder.getAddress(new AMap.LngLat(e.lnglat.lng, e.lnglat.lat), function(status, result) {
            if (status == 'complete') {
              that.geographiclocationInformation = result.regeocode.formattedAddress
            } else {
              that.geographiclocationInformation = '暂无信息'
            }
          })
        })
        map.on('zoomstart', function(e) {
          that.mapZoomLevel = map.getZoom()
        })
      }).catch(e => {
        console.log('错误', e)
      })
    },
    //获取当前位置信息
    getCityService() {
      let that = this
      this.AMap.plugin('AMap.CitySearch', function() {
        let citySearch  = new AMap.CitySearch()
        citySearch.getLocalCity(function(status, result) {
          console.log(result)
          if (status == 'complete') {
            // onComplete(result)
            that.mapCity = result.city
            // that.map.setCenter([result.bounds.northEast.lng, result.bounds.northEast.lat]
            that.map.setCenter([116.255270, 36.580688])
          } else {
            // onError(result)
          }
        })
      })
    },
    //查询地址信息
    handleSearch(index) {
      let that = this
      if (!util.isNullEmpty(that.city)){
        this.AMap.plugin('AMap.PlaceSearch', function() {
          var autoOptions = {
            city: index
          }
          var placeSearch = new AMap.PlaceSearch(autoOptions)
          placeSearch.search(that.city, function(status, result) {
            // console.log(result.poiList.pois)
            // 搜索成功时，result即是对应的匹配数据
            if (status == 'complete') {
              that.addressList = result.poiList.pois
            }
          })
        })
      }else {
        this.AMap.plugin('AMap.PlaceSearch', function() {
          let autoOptions = {
            city: '全国'
          }
          let placeSearch = new AMap.PlaceSearch(autoOptions)
          placeSearch.search(index, function(status, result) {
            // 搜索成功时，result即是对应的匹配数据
            if (status == 'complete') {
              that.addressList = result.poiList.pois
              that.map.setCenter([result.poiList.pois[0].location.lng, result.poiList.pois[0].location.lat])
              that.map.setZoom(9)
            }
          })
        })
      }
    },
    //点击搜索
    selectAddress(item) {
      // console.log(item)
      this.geographiclocationInformation = item.address
      // this.lng = item.location.lng
      // this.lat = item.location.lat
      this.map.setCenter([item.location.lng, item.location.lat])
    },
    //保存范围数据
    saveLatOrLng(){
      this.map.destroy()
      if (this.mouseToolList.length != 0){
        console.log(this.mouseToolList)
        this.form.scope = JSON.stringify(this.mouseToolList)
      }
      console.log(this.form.scope)
      // this.form.latitudes = this.lat
      // this.form.longitude = this.lng
      this.coordinate = false
    },
    //绘制厂区范围
    drawFactoryArea(){
      this.$message.success('请在地图上开始绘制')
      let that = this
      this.overlays = []
      this.map.plugin(["AMap.MouseTool"],function(){
        let mouseTool = new AMap.MouseTool(that.map);
        mouseTool.polygon({
          fillColor:'#00b0ff',
          strokeColor:'#80d8ff'
          //同Polygon的Option设置
        });
        that.mouseToolList = []
        mouseTool.on('draw',function(e){
          // console.log(e.obj)
          // console.log(e.obj._opts.path);
          that.mouseToolList.push(e.obj._opts.path)
          that.overlays.push(e.obj);
          // console.log(that.overlays);

        })
      });
    },
    //清空数据
    empty(){
      this.map.remove(this.overlays)
      this.overlays = []
      this.mouseToolList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加厂区范围";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFactoryArea(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改厂区范围";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFactoryArea(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFactoryArea(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除厂区范围编号为"' + ids + '"的数据项？').then(function() {
        return delFactoryArea(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('factoryArea/factoryArea/export', {
        ...this.queryParams
      }, `factoryArea_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.myMap {
  width: 100%;
  height: 100%;
}

.map_list {
  width: 100%;
  padding: 0 10px
}

.map_empty {
  padding: 0 10px
}

.map_list:hover {
  background-color: #e5e5e5;
}
</style>
